import {
  Component,
  OnInit,
  ViewChild,
  Input,
  Output,
  EventEmitter,
  OnChanges
} from "@angular/core";
import { NzFormatEmitEvent, NzTreeNodeOptions } from "ng-zorro-antd";
import { NzTreeComponent } from "ng-zorro-antd/tree";
import { TreeNode } from "../one-map";

@Component({
  selector: "app-map-tree",
  templateUrl: "./map-tree.component.html",
  styleUrls: ["./map-tree.component.scss"]
})
export class MapTreeComponent implements OnChanges {
  @ViewChild("nzTreeComponent", { static: false })
  nzTreeComponent: NzTreeComponent;
  @Input() mapTreeData: NzTreeNodeOptions[];
  @Output() nodeSelected = new EventEmitter();
  @Output() checkboxChange = new EventEmitter();
  toggle: boolean;

  constructor() { }

  ngOnChanges(): void { }

  onSelect(event): void {
    console.log(event);
    const nodeClick = event.node;
    if (!nodeClick.isLeaf) {
      nodeClick.isExpanded = !nodeClick.isExpanded;
      this.checkNodeExpand(nodeClick);
    } else {
      nodeClick.isChecked = true;
      this.nodeSelected.emit({
        ...nodeClick.origin,
        level: nodeClick.level
      });
    }
  }

  onCheckboxChange(event): void {
    const nodeClick = event.node;
    this.checkboxChange.emit({
      ...nodeClick.origin,
      level: nodeClick.level
    });
  }

  onExpand(event) {
    // console.log(event);
    // this.checkNodeExpand(event.node);
  }

  checkNodeExpand(nodeClick) {
    const list = this.nzTreeComponent.getExpandedNodeList();
    list.map(node => {
      if (node.key != nodeClick.key) {
        node.isExpanded = false;
      }
    });
  }
}
